package lt.ntec.danblog.server.core.helpers;

import info.bliki.wiki.model.WikiModel;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.BodyContent;
import java.io.IOException;

public class FormatWiki extends BodyTagSupport {

    /**
     *
     */
    private static final long serialVersionUID = 1672599545690288065L;

    public FormatWiki() {
    }

    public int doAfterBody() throws JspTagException {
        try {
            BodyContent body = getBodyContent();
            JspWriter out = body.getEnclosingWriter();
            /* Get Input Value */
            String textValue = body.getString().trim();

            /* Output Formatted Value */
            out.println(formatValue(textValue));
        } catch (IOException e) {
            throw new JspTagException(e.toString());
        }
        return SKIP_BODY;
    }

    public int doEndTag() throws JspTagException {
        return EVAL_PAGE;
    }

    private String formatValue(String _input) {
        String formattedValue = _input;
        String path = pageContext.getServletContext().getContextPath();
        try {
            WikiModel wikiModel = new WikiModel(path + "/${image}", path
                    + "/${title}");
            formattedValue = wikiModel.render(_input);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return formattedValue;
    }
}